package com.smartpro.mis.modular.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.smartpro.mis.core.base.controller.BaseController;
import com.smartpro.mis.modular.business.neo4jEntity.DistributorExpireRelationship;
import com.smartpro.mis.modular.business.neo4jEntity.DistributorProtectRelationship;
import com.smartpro.mis.modular.business.neo4jEntity.N4jDistributor;
import com.smartpro.mis.modular.business.neo4jEntity.N4jUser;
import com.smartpro.mis.modular.business.service.IMessageService;
import com.smartpro.mis.modular.business.service.IPositionService;
import com.smartpro.mis.modular.business.service.IUserService;
import com.smartpro.mis.modular.system.dao.ClickDistributorRelationRepository;
import com.smartpro.mis.modular.system.dao.DistributorExpireRelationRepository;
import com.smartpro.mis.modular.system.dao.DistributorProtectRelationRepository;
import com.smartpro.mis.modular.system.dao.N4jDistributorRepository;
import com.smartpro.mis.modular.system.model.Message;
import com.smartpro.mis.modular.system.model.Position;
import com.smartpro.mis.modular.system.model.User;
import com.smartpro.mis.rest.modular.auth.controller.dto.ResponseBean;
import com.smartpro.mis.rest.modular.auth.util.JWTToken;
import com.smartpro.mis.rest.modular.auth.util.JwtTokenUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.smartpro.mis.modular.system.model.Distributor;
import com.smartpro.mis.modular.business.service.IDistributorService;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 推广员控制器
 *
 * @author Mengiy
 * @Date 2019-05-07 21:48:53
 */
@RestController
@RequestMapping("/api/service/distributor")

public class DistributorController extends BaseController {


    @Autowired
    private IDistributorService distributorService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IMessageService messageService;

    @Autowired
    private IPositionService positionService;


    @Autowired
    private N4jDistributorRepository n4jDistributorRepository;

    @Autowired
    private DistributorExpireRelationRepository distributorExpireRelationRepository;

    @Autowired
    DistributorProtectRelationRepository distributorProtectRelationRepository;



    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取推广员列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    @RequiresAuthentication
    public Object list(String condition) {
        return distributorService.selectList(null);
    }


    /**
     * 获取全部推广员列表
     */
    @ApiOperation(value = "获取全部推广员列表",notes = "运营端获取全部推广员列表")
    @RequestMapping(value = "/getDistributorList",method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object getDistributorList() {
        return new ResponseBean(200,"query success",distributorService.selectList(null));
    }

    /**
     * 多条件查询推广员列表
     */
    @ApiOperation(value = "多条件查询推广员列表",notes="多条件筛选推广员列表" )
    @ApiImplicitParam(name = "params", value = "json格式查询条件,如状态status,0:已申请,1:审批通过,2:审批未通过,3:被清退", required = true, dataType = "Map")
    @RequestMapping(value = "/mulQuery",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object mulQuery(@RequestBody Map params) {
        return new ResponseBean(200,"operation success",distributorService.selectByMap(params));
    }



    /**
     * 申请成为推广员
     */
    @ApiOperation(value ="申请成为推广员",notes="登录用户申请成为推广员")
    @ApiImplicitParam(name = "disInfo", value = "推广员详情", required = true, dataType = "JSONObject")
    @RequestMapping(value = "/postApplyForDistributor",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object postApplyForDistributor(HttpServletRequest request, @RequestBody JSONObject disInfo) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
//        String authorization = request.getUserPrincipal().getName();
        JwtTokenUtil jwt = new JwtTokenUtil();
        String username = jwt.getUsernameFromToken(authorization);
//        System.out.println("###########  username from token: "+ username);
        Map<String,Object> condtion = new HashMap();
        condtion.put("wechat",username);
        User user = this.userService.selectByMap(condtion).get(0);
        Distributor distributor;
        distributor = this.distributorService.selectById(user.getUserID());
        if(null != distributor){
            return new ResponseBean(400, "cannot apply again", distributor);
        }
        distributor = new Distributor();
        String belongTo = disInfo.getString("belongTo");
        String childName = disInfo.getString("childName");
        int gender = disInfo.getInteger("gender");
        String birthday = disInfo.getString("birthday");
        String mobile = disInfo.getString("mobile");
        String province = disInfo.getString("province");
        String city = disInfo.getString("city");
        String address = disInfo.getString("address");
        String comments = disInfo.getString("comments");
        user.setChildName(childName);
        user.setGender(gender);
        user.setChildBirthday(birthday);
        user.setMobile(mobile);
        user.setProvince(province);
        user.setCity(city);
        user.setAddress(address);


        distributor.setUserID(user.getUserID());
        distributor.setApplyForComments(comments);
        distributor.setBelongToCompany(belongTo);
        distributor.setCreateTime(sdf.format(new Date()));
        distributor.setStatus(0);

        Message message = new Message();
        message.setCreateTime(sdf.format(new Date()));
        message.setMessageType(0);
        message.setContent(comments);
        message.setSenderID(user.getUserID());
        message.setReceiverID(-1);
        message.setIsRead(1);
       try {
           this.userService.updateById(user);
           distributorService.insertOrUpdate(distributor);
           this.messageService.insert(message);
           return new ResponseBean(200, "apply submit success", disInfo);
       }catch (Exception e){
           return new ResponseBean(400, "apply submit fail", e.getStackTrace());
       }

    }


    /**
     * 添加推广员
     */
    @ApiOperation(value ="添加推广员",notes="登录用户申请成为推广员")
    @ApiImplicitParam(name = "disInfo", value = "推广员详情", required = true, dataType = "JSONObject")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object add(HttpServletRequest request, @RequestBody JSONObject disInfo) {
        System.out.println("###########  jsonData: "+ disInfo.toJSONString());
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
//        String authorization = request.getUserPrincipal().getName();
        JwtTokenUtil jwt = new JwtTokenUtil();
        String username = jwt.getUsernameFromToken(authorization);
        System.out.println("###########  username from token: "+ username);
        Map<String,Object> condtion = new HashMap();
        condtion.put("wechat",username);
        User user = this.userService.selectByMap(condtion).get(0);
        Distributor distributor;
        distributor = this.distributorService.selectById(user.getUserID());
        if(null != distributor){
            return new ResponseBean(400, "cannot apply again.", distributor);
        }
        distributor = new Distributor();
        String belongTo = disInfo.getString("belongTo");
        String childName = disInfo.getString("childName");
        int gender = disInfo.getInteger("gender");
        String birthday = disInfo.getString("birthday");
        String mobile = disInfo.getString("mobile");
        String province = disInfo.getString("province");
        String city = disInfo.getString("city");
        String address = disInfo.getString("address");
        String comments = disInfo.getString("comments");
        user.setChildName(childName);
        user.setGender(gender);
        user.setChildBirthday(birthday);
        user.setMobile(mobile);
        user.setProvince(province);
        user.setCity(city);
        user.setAddress(address);


        distributor.setUserID(user.getUserID());
        distributor.setApplyForComments(comments);
        distributor.setBelongToCompany(belongTo);
        distributor.setCreateTime(sdf.format(new Date()));
        distributor.setStatus(0);

        Message message = new Message();
        message.setCreateTime(sdf.format(new Date()));
        message.setMessageType(0);
        message.setContent(comments);
        message.setSenderID(user.getUserID());
        message.setReceiverID(-1);
        message.setIsRead(1);
        try {
            this.userService.updateById(user);
            distributorService.insertOrUpdate(distributor);
            this.messageService.insert(message);
            return new ResponseBean(200, "apply submit success", disInfo);
        }catch (Exception e){
            return new ResponseBean(400, "apply submit fail", e.getStackTrace());
        }

    }


    /**
     * 删除推广员
     */
    @ApiOperation(value ="删除推广员")
    @ApiImplicitParam(name = "distributorId", value = "推广员编号", required = true, dataType = "Integer")
    @RequestMapping(value = "/delete",method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object delete(@RequestParam Integer distributorId) {
        distributorService.deleteById(distributorId);
        return SUCCESS_TIP;
    }

    /**
     * 修改推广员
     */
    @ApiOperation(value ="修改推广员")
    @ApiImplicitParam(name = "distributor", value = "推广员详情", required = true, dataType = "Distributor")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object update(HttpServletRequest request,@RequestBody Distributor distributor) {

        distributor.setModifyTime(sdf.format(new Date()));
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        JwtTokenUtil jwt = new JwtTokenUtil();
        String username = jwt.getUsernameFromToken(authorization);
        Map<String,Object> condtion = new HashMap();
        condtion.put("wechat",username);
        User user = this.userService.selectByMap(condtion).get(0);
        distributor.setOperatorID(user.getUserID());
        try {
            distributorService.updateById(distributor);
            return new ResponseBean(200, "update success", distributor);
        }catch (Exception e){
            return new ResponseBean(400, "update fail", e.getStackTrace());
        }
    }

    /**
     * 拒绝推广员申请
     */
    @ApiOperation(value ="拒绝推广员申请",notes = "需要userID、messageID、reason")
    @ApiImplicitParam(name = "jsonData", value = "拒绝操作的参数数据", required = true, dataType = "JSONObject")
    @RequestMapping(value = "/patchRejectApplication",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object patchRejectApplication(HttpServletRequest request,@RequestBody JSONObject jsonData) {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        JwtTokenUtil jwt = new JwtTokenUtil();
        String username = jwt.getUsernameFromToken(authorization);
        Map<String,Object> condtion = new HashMap();
        condtion.put("wechat",username);
        User user = this.userService.selectByMap(condtion).get(0);

        Message message = this.messageService.selectById(jsonData.getInteger("messageID"));
        message.setMessageType(1);
        message.setContent(jsonData.getString("reason"));
        message.setModifyTime(sdf.format(new Date()));
        int userID = message.getSenderID();
        Distributor distributor = this.distributorService.selectById(userID);
        distributor.setOperatorID(user.getUserID());
        distributor.setStatus(2);
        distributor.setModifyTime(sdf.format(new Date()));
        distributor.setRejectReason(jsonData.getString("reason"));
        try {
            distributorService.updateById(distributor);
            messageService.updateById(message);
            return new ResponseBean(200, "operation success", distributor);
        }catch (Exception e){
            return new ResponseBean(400, "operation fail", e.getStackTrace());
        }
    }


    /**
     * 接收推广员申请
     */
    @ApiOperation(value ="接收推广员申请",notes = "需要userID、messageID、positionID")
    @ApiImplicitParam(name = "jsonData", value = "接收操作的参数数据：消息编号、岗位编号", required = true, dataType = "JSONObject")
    @RequestMapping(value = "/patchAcceptApplication",method = RequestMethod.POST)
    @ResponseBody
    @RequiresAuthentication
    public Object patchAcceptApplication(HttpServletRequest request,@RequestBody JSONObject jsonData) {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        JwtTokenUtil jwt = new JwtTokenUtil();
        String username = jwt.getUsernameFromToken(authorization);
        Map<String,Object> condtion = new HashMap();
        condtion.put("wechat",username);
        User user = this.userService.selectByMap(condtion).get(0);

        Message message = this.messageService.selectById(jsonData.getInteger("messageID"));
        message.setMessageType(2);
        message.setContent("接受推广员申请");
        message.setModifyTime(sdf.format(new Date()));
        int userID = message.getSenderID();
        Distributor distributor = this.distributorService.selectById(userID);
        distributor.setOperatorID(user.getUserID());
        distributor.setStatus(1);
        distributor.setModifyTime(sdf.format(new Date()));
        distributor.setPositionID(jsonData.getInteger("positionID"));
        try {
            distributorService.updateById(distributor);
            messageService.updateById(message);
            /**
             * 建立neo4j推广员，并设置有效期，保护期
             */
            N4jDistributor n4jDistributor = new N4jDistributor(userID);
            this.n4jDistributorRepository.save(n4jDistributor);
            //新增推广员不需要建立有效期和保护期
//            Position position = this.positionService.selectById(jsonData.getInteger("positionID"));
            //用户如果自己是推广员，那么从成为推广员时，用户就与自己绑定了推广关系，保护期和有效期为永久。
            N4jDistributor n4jDistributor2 = this.n4jDistributorRepository.findByDistributorID(userID);
            if(null==n4jDistributor2){
                DistributorExpireRelationship distributorExpireRelationship = new DistributorExpireRelationship(sdf.format(new Date()),-999,n4jDistributor,new N4jUser(userID));
                DistributorProtectRelationship distributorProtectRelationship = new DistributorProtectRelationship(sdf.format(new Date()),-999,n4jDistributor,new N4jUser(userID));
                distributorExpireRelationRepository.save(distributorExpireRelationship);
                distributorProtectRelationRepository.save(distributorProtectRelationship);
            }

            return new ResponseBean(200, "operation success", distributor);
        }catch (Exception e){
            return new ResponseBean(400, "operation fail", e.getStackTrace());
        }
    }

    /**
     * 推广员详情
     */
    @ApiOperation(value ="推广员详情")
    @ApiImplicitParam(name = "distributorId", value = "推广员编号", required = true, dataType = "Integer")
    @RequestMapping(value = "/detail/{distributorId}",method = RequestMethod.GET)
    @ResponseBody
    @RequiresAuthentication
    public Object detail(@PathVariable("distributorId") Integer distributorId) {
        try {

            Distributor distributor = distributorService.selectById(distributorId);

            return new ResponseBean(200, "view success", distributor);
        } catch (Exception e) {
            return new ResponseBean(400, "view fail", e.getStackTrace());
        }
    }
}
